using Microsoft.Extensions.Logging;
using CollabApp.Domain.Entities.Game;
using CollabApp.Domain.Services.Game;
using CollabApp.Application.Interfaces;
using System.Text.Json;

namespace CollabApp.Application.Services.Game;

/// <summary>
/// 圈地游戏道具系统服务实现
/// 负责管理游戏中的四种核心道具：闪电、护盾、炸弹、幽灵
/// 实现智能刷新机制、道具效果管理和平衡性控制
/// </summary>
public class PowerUpService : IPowerUpService
{
    private readonly ILogger<PowerUpService> _logger;
    private readonly IRedisService _redisService;
    private readonly IGameStateService _gameStateService;
    private readonly ITerritoryService _territoryService;
    private readonly Random _random;

    // Redis 键前缀
    private const string POWERUPS_KEY = "game:{0}:powerups";
    private const string PLAYER_POWERUPS_KEY = "game:{0}:player_powerups";
    private const string ACTIVE_EFFECTS_KEY = "game:{0}:active_effects";
    private const string SPAWN_CONFIG_KEY = "powerup_config:{0}";

    public PowerUpService(
        ILogger<PowerUpService> logger,
        IRedisService redisService,
        IGameStateService gameStateService,
        ITerritoryService territoryService)
    {
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        _redisService = redisService ?? throw new ArgumentNullException(nameof(redisService));
        _gameStateService = gameStateService ?? throw new ArgumentNullException(nameof(gameStateService));
        _territoryService = territoryService ?? throw new ArgumentNullException(nameof(territoryService));
        _random = new Random();
    }

    /// <summary>
    /// 智能生成道具
    /// 根据玩家密度和领地分布调整刷新位置，优先在无人领地区域生成
    /// </summary>
    public async Task<List<PowerUpInstance>> SpawnPowerUpsAsync(Guid gameId, bool excludeOccupiedAreas = true)
    {
        try
        {
            _logger.LogInformation("开始智能生成道具 - 游戏ID: {GameId}", gameId);

            // 获取游戏状态和配置
            var gameState = await _gameStateService.GetGameStateAsync(gameId);
            if (gameState == null)
            {
                _logger.LogWarning("游戏状态不存在 - 游戏ID: {GameId}", gameId);
                return new List<PowerUpInstance>();
            }

            var config = GetPowerUpConfig("standard"); // 暂时使用标准模式
            var existingPowerUps = await GetMapPowerUpsAsync(gameId);

            // 检查是否需要生成新道具
            if (existingPowerUps.Count >= config.MaxConcurrentPowerUps)
            {
                _logger.LogDebug("地图道具已达上限 - 当前: {Current}, 最大: {Max}", 
                    existingPowerUps.Count, config.MaxConcurrentPowerUps);
                return new List<PowerUpInstance>();
            }

            // 计算需要生成的道具数量
            int spawnCount = Math.Min(3, config.MaxConcurrentPowerUps - existingPowerUps.Count);
            var newPowerUps = new List<PowerUpInstance>();

            for (int i = 0; i < spawnCount; i++)
            {
                var powerUpType = SelectRandomPowerUpType(config.SpawnWeights);
                var spawnPosition = await FindOptimalSpawnPosition(gameId, excludeOccupiedAreas);

                if (spawnPosition == null)
                {
                    _logger.LogWarning("无法找到合适的道具生成位置 - 游戏ID: {GameId}", gameId);
                    continue;
                }

                var powerUp = new PowerUpInstance
                {
                    Id = Guid.NewGuid(),
                    Type = powerUpType,
                    Position = spawnPosition,
                    SpawnTime = DateTime.UtcNow,
                    IsActive = true,
                    Color = GetPowerUpColor(powerUpType),
                    Icon = GetPowerUpIcon(powerUpType),
                    Properties = GetPowerUpProperties(powerUpType)
                };

                newPowerUps.Add(powerUp);
            }

            // 保存新生成的道具到Redis
            if (newPowerUps.Any())
            {
                var allPowerUps = existingPowerUps.Concat(newPowerUps).ToList();
                var serialized = JsonSerializer.Serialize(allPowerUps);
                await _redisService.StringSetAsync(string.Format(POWERUPS_KEY, gameId), serialized, TimeSpan.FromHours(1));

                _logger.LogInformation("成功生成 {Count} 个道具 - 游戏ID: {GameId}", newPowerUps.Count, gameId);
            }

            return newPowerUps;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "生成道具时发生异常 - 游戏ID: {GameId}", gameId);
            throw;
        }
    }

    /// <summary>
    /// 玩家拾取道具
    /// 玩家接近道具时自动拾取，每个玩家最多持有1个道具
    /// </summary>
    public async Task<PowerUpPickupResult> PickupPowerUpAsync(Guid gameId, Guid playerId, Guid powerUpId, Position playerPosition)
    {
        try
        {
            _logger.LogInformation("玩家拾取道具 - 游戏ID: {GameId}, 玩家ID: {PlayerId}, 道具ID: {PowerUpId}", 
                gameId, playerId, powerUpId);

            var result = new PowerUpPickupResult();

            // 获取地图道具
            var mapPowerUps = await GetMapPowerUpsAsync(gameId);
            var targetPowerUp = mapPowerUps.FirstOrDefault(p => p.Id == powerUpId && p.IsActive);

            if (targetPowerUp == null)
            {
                result.Errors.Add("道具不存在或已被拾取");
                return result;
            }

            // 检查距离（拾取范围15像素）
            var distance = CalculateDistance(playerPosition, targetPowerUp.Position);
            if (distance > 15)
            {
                result.Errors.Add($"距离道具过远，需要在15像素内才能拾取，当前距离: {distance:F1}");
                return result;
            }

            // 检查玩家当前道具状态
            var currentPowerUp = await GetPlayerPowerUpAsync(gameId, playerId);
            string? replacedPowerUp = null;

            if (currentPowerUp?.PowerUpType.HasValue == true)
            {
                replacedPowerUp = currentPowerUp.PowerUpType.ToString();
                result.Messages.Add($"替换了原有道具: {replacedPowerUp}");
            }

            // 更新玩家道具状态
            var playerPowerUp = new PlayerPowerUp
            {
                PlayerId = playerId,
                PowerUpType = targetPowerUp.Type,
                ObtainedTime = DateTime.UtcNow,
                CanUse = true
            };

            var serializedPlayerPowerUp = JsonSerializer.Serialize(playerPowerUp);
            await _redisService.StringSetAsync(
                $"{string.Format(PLAYER_POWERUPS_KEY, gameId)}:{playerId}", 
                serializedPlayerPowerUp, 
                TimeSpan.FromHours(1));

            // 从地图移除道具
            targetPowerUp.IsActive = false;
            mapPowerUps.RemoveAll(p => p.Id == powerUpId);
            var serializedMapPowerUps = JsonSerializer.Serialize(mapPowerUps);
            await _redisService.StringSetAsync(string.Format(POWERUPS_KEY, gameId), serializedMapPowerUps, TimeSpan.FromHours(1));

            result.Success = true;
            result.PowerUpType = targetPowerUp.Type;
            result.ReplacedPowerUp = replacedPowerUp;
            result.Messages.Add($"成功拾取 {GetPowerUpName(targetPowerUp.Type)} 道具");

            _logger.LogInformation("道具拾取成功 - 玩家ID: {PlayerId}, 道具类型: {PowerUpType}", 
                playerId, targetPowerUp.Type);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "拾取道具时发生异常 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", gameId, playerId);
            throw;
        }
    }

    /// <summary>
    /// 使用闪电道具
    /// 效果：移动速度提升60%，持续8秒，但画线轨迹更粗（3像素）更易被发现
    /// </summary>
    public async Task<LightningUseResult> UseLightningPowerUpAsync(Guid gameId, Guid playerId)
    {
        try
        {
            _logger.LogInformation("使用闪电道具 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", gameId, playerId);

            var result = new LightningUseResult();

            // 检查玩家是否拥有闪电道具
            var playerPowerUp = await GetPlayerPowerUpAsync(gameId, playerId);
            if (playerPowerUp?.PowerUpType != TerritoryGamePowerUpType.Lightning)
            {
                result.Errors.Add("玩家未持有闪电道具");
                return result;
            }

            if (!playerPowerUp.CanUse)
            {
                result.Errors.Add("道具当前无法使用");
                return result;
            }

            // 创建闪电效果
            var lightningEffect = new ActivePowerUpEffect
            {
                EffectId = Guid.NewGuid(),
                PlayerId = playerId,
                Type = TerritoryGamePowerUpType.Lightning,
                Name = "闪电加速",
                StartTime = DateTime.UtcNow,
                DurationSeconds = 8,
                EndTime = DateTime.UtcNow.AddSeconds(8),
                IsActive = true,
                Effects = new Dictionary<string, float>
                {
                    { "SpeedMultiplier", 1.6f },
                    { "TrailThickness", 3f }
                }
            };

            // 保存效果到Redis
            var activeEffects = await GetActiveEffectsAsync(gameId, playerId);
            // 移除已有的闪电效果（如果存在）
            activeEffects.RemoveAll(e => e.Type == TerritoryGamePowerUpType.Lightning);
            activeEffects.Add(lightningEffect);

            var serializedEffects = JsonSerializer.Serialize(activeEffects);
            await _redisService.StringSetAsync(
                $"{string.Format(ACTIVE_EFFECTS_KEY, gameId)}:{playerId}",
                serializedEffects,
                TimeSpan.FromHours(1));

            // 消耗道具
            await ConsumePowerUpAsync(gameId, playerId);

            result.Success = true;
            result.SpeedMultiplier = 1.6f;
            result.DurationSeconds = 8;
            result.TrailThickness = 3f;
            result.EffectEndTime = lightningEffect.EndTime;
            result.Messages.Add("闪电道具激活！移动速度提升60%，持续8秒");
            result.Messages.Add("警告：你的轨迹会变得更粗，更容易被敌人发现");

            _logger.LogInformation("闪电道具使用成功 - 玩家ID: {PlayerId}, 效果结束时间: {EndTime}", 
                playerId, lightningEffect.EndTime);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "使用闪电道具时发生异常 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", gameId, playerId);
            throw;
        }
    }

    /// <summary>
    /// 使用护盾道具
    /// 效果：免疫一次截断攻击，持续12秒或触发一次保护，使用时移动速度降低10%
    /// </summary>
    public async Task<ShieldUseResult> UseShieldPowerUpAsync(Guid gameId, Guid playerId)
    {
        try
        {
            _logger.LogInformation("使用护盾道具 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", gameId, playerId);

            var result = new ShieldUseResult();

            // 检查玩家是否拥有护盾道具
            var playerPowerUp = await GetPlayerPowerUpAsync(gameId, playerId);
            if (playerPowerUp?.PowerUpType != TerritoryGamePowerUpType.Shield)
            {
                result.Errors.Add("玩家未持有护盾道具");
                return result;
            }

            if (!playerPowerUp.CanUse)
            {
                result.Errors.Add("道具当前无法使用");
                return result;
            }

            // 创建护盾效果
            var shieldEffect = new ActivePowerUpEffect
            {
                EffectId = Guid.NewGuid(),
                PlayerId = playerId,
                Type = TerritoryGamePowerUpType.Shield,
                Name = "能量护盾",
                StartTime = DateTime.UtcNow,
                DurationSeconds = 12,
                EndTime = DateTime.UtcNow.AddSeconds(12),
                IsActive = true,
                Effects = new Dictionary<string, float>
                {
                    { "SpeedMultiplier", 0.9f }, // 10%速度降低
                    { "BlocksRemaining", 1f }    // 可阻挡1次攻击
                }
            };

            // 保存效果到Redis
            var activeEffects = await GetActiveEffectsAsync(gameId, playerId);
            // 移除已有的护盾效果（如果存在）
            activeEffects.RemoveAll(e => e.Type == TerritoryGamePowerUpType.Shield);
            activeEffects.Add(shieldEffect);

            var serializedEffects = JsonSerializer.Serialize(activeEffects);
            await _redisService.StringSetAsync(
                $"{string.Format(ACTIVE_EFFECTS_KEY, gameId)}:{playerId}",
                serializedEffects,
                TimeSpan.FromHours(1));

            // 消耗道具
            await ConsumePowerUpAsync(gameId, playerId);

            result.Success = true;
            result.DurationSeconds = 12;
            result.SpeedPenalty = 0.9f;
            result.EffectEndTime = shieldEffect.EndTime;
            result.BlocksRemaining = 1;
            result.Messages.Add("护盾道具激活！可免疫一次致命攻击");
            result.Messages.Add("注意：护盾激活期间移动速度降低10%");

            _logger.LogInformation("护盾道具使用成功 - 玩家ID: {PlayerId}, 效果结束时间: {EndTime}", 
                playerId, shieldEffect.EndTime);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "使用护盾道具时发生异常 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", gameId, playerId);
            throw;
        }
    }

    /// <summary>
    /// 使用炸弹道具
    /// 效果：以当前位置为中心，半径30像素范围变成领地，只能在中立区域或己方领地使用
    /// </summary>
    public async Task<BombUseResult> UseBombPowerUpAsync(Guid gameId, Guid playerId, Position targetPosition)
    {
        try
        {
            _logger.LogInformation("使用炸弹道具 - 游戏ID: {GameId}, 玩家ID: {PlayerId}, 位置: ({X}, {Y})", 
                gameId, playerId, targetPosition.X, targetPosition.Y);

            var result = new BombUseResult();

            // 检查玩家是否拥有炸弹道具
            var playerPowerUp = await GetPlayerPowerUpAsync(gameId, playerId);
            if (playerPowerUp?.PowerUpType != TerritoryGamePowerUpType.Bomb)
            {
                result.Errors.Add("玩家未持有炸弹道具");
                return result;
            }

            if (!playerPowerUp.CanUse)
            {
                result.Errors.Add("道具当前无法使用");
                return result;
            }

            // 检查目标位置是否合法（不在敌方领地）
            var territoryOwnership = await _territoryService.CheckTerritoryOwnershipAsync(gameId, targetPosition);
            if (territoryOwnership.OwnerId != null && territoryOwnership.OwnerId != playerId)
            {
                result.Errors.Add("无法在敌方领地使用炸弹道具");
                return result;
            }

            // 计算爆炸范围内的新领地
            const float explosionRadius = 30f;
            var newTerritoryPoints = GenerateCirclePoints(targetPosition, explosionRadius);
            
            // 模拟领地占领（这里简化处理，实际需要调用具体的领地更新方法）
            // 实际实现中应该调用具体的领地服务方法来更新领地状态

            // 计算获得的面积
            var areaGained = (decimal)(Math.PI * explosionRadius * explosionRadius);

            // 消耗道具
            await ConsumePowerUpAsync(gameId, playerId);

            result.Success = true;
            result.ExplosionCenter = targetPosition;
            result.ExplosionRadius = explosionRadius;
            result.AreaGained = areaGained;
            result.NewTerritory = newTerritoryPoints;
            result.Messages.Add($"炸弹道具生效！获得 {areaGained:F0} 平方像素领地");

            _logger.LogInformation("炸弹道具使用成功 - 玩家ID: {PlayerId}, 获得面积: {Area}", 
                playerId, areaGained);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "使用炸弹道具时发生异常 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", gameId, playerId);
            throw;
        }
    }

    /// <summary>
    /// 使用幽灵道具
    /// 效果：10秒内可以穿越敌方轨迹而不死亡，但不能圈地
    /// </summary>
    public async Task<GhostUseResult> UseGhostPowerUpAsync(Guid gameId, Guid playerId)
    {
        try
        {
            _logger.LogInformation("使用幽灵道具 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", gameId, playerId);

            var result = new GhostUseResult();

            // 检查玩家是否拥有幽灵道具
            var playerPowerUp = await GetPlayerPowerUpAsync(gameId, playerId);
            if (playerPowerUp?.PowerUpType != TerritoryGamePowerUpType.Ghost)
            {
                result.Errors.Add("玩家未持有幽灵道具");
                return result;
            }

            if (!playerPowerUp.CanUse)
            {
                result.Errors.Add("道具当前无法使用");
                return result;
            }

            // 创建幽灵效果
            var ghostEffect = new ActivePowerUpEffect
            {
                EffectId = Guid.NewGuid(),
                PlayerId = playerId,
                Type = TerritoryGamePowerUpType.Ghost,
                Name = "幽灵形态",
                StartTime = DateTime.UtcNow,
                DurationSeconds = 10,
                EndTime = DateTime.UtcNow.AddSeconds(10),
                IsActive = true,
                Effects = new Dictionary<string, float>
                {
                    { "CanPassThroughTrails", 1f },  // 可穿越轨迹
                    { "CanDrawTerritory", 0f }       // 不能圈地
                }
            };

            // 保存效果到Redis
            var activeEffects = await GetActiveEffectsAsync(gameId, playerId);
            // 移除已有的幽灵效果（如果存在）
            activeEffects.RemoveAll(e => e.Type == TerritoryGamePowerUpType.Ghost);
            activeEffects.Add(ghostEffect);

            var serializedEffects = JsonSerializer.Serialize(activeEffects);
            await _redisService.StringSetAsync(
                $"{string.Format(ACTIVE_EFFECTS_KEY, gameId)}:{playerId}",
                serializedEffects,
                TimeSpan.FromHours(1));

            // 消耗道具
            await ConsumePowerUpAsync(gameId, playerId);

            result.Success = true;
            result.DurationSeconds = 10;
            result.EffectEndTime = ghostEffect.EndTime;
            result.CanDrawWhileGhost = false;
            result.Messages.Add("幽灵道具激活！10秒内可穿越敌方轨迹");
            result.Messages.Add("警告：幽灵状态下无法进行圈地操作");

            _logger.LogInformation("幽灵道具使用成功 - 玩家ID: {PlayerId}, 效果结束时间: {EndTime}", 
                playerId, ghostEffect.EndTime);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "使用幽灵道具时发生异常 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", gameId, playerId);
            throw;
        }
    }

    /// <summary>
    /// 获取玩家当前道具
    /// </summary>
    public async Task<PlayerPowerUp?> GetPlayerPowerUpAsync(Guid gameId, Guid playerId)
    {
        try
        {
            var key = $"{string.Format(PLAYER_POWERUPS_KEY, gameId)}:{playerId}";
            var serialized = await _redisService.StringGetAsync(key);
            if (string.IsNullOrEmpty(serialized)) return null;
            return JsonSerializer.Deserialize<PlayerPowerUp>(serialized);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取玩家道具时发生异常 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", gameId, playerId);
            return null;
        }
    }

    /// <summary>
    /// 获取玩家活跃道具效果
    /// </summary>
    public async Task<List<ActivePowerUpEffect>> GetActiveEffectsAsync(Guid gameId, Guid playerId)
    {
        try
        {
            var key = $"{string.Format(ACTIVE_EFFECTS_KEY, gameId)}:{playerId}";
            var serialized = await _redisService.StringGetAsync(key);
            if (string.IsNullOrEmpty(serialized)) return new List<ActivePowerUpEffect>();
            
            var effects = JsonSerializer.Deserialize<List<ActivePowerUpEffect>>(serialized) ?? new List<ActivePowerUpEffect>();
            return effects.Where(e => e.IsActive && e.EndTime > DateTime.UtcNow).ToList();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取活跃效果时发生异常 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", gameId, playerId);
            return new List<ActivePowerUpEffect>();
        }
    }

    /// <summary>
    /// 获取地图上所有道具
    /// </summary>
    public async Task<List<PowerUpInstance>> GetMapPowerUpsAsync(Guid gameId)
    {
        try
        {
            var serialized = await _redisService.StringGetAsync(string.Format(POWERUPS_KEY, gameId));
            if (string.IsNullOrEmpty(serialized)) return new List<PowerUpInstance>();
            
            var powerUps = JsonSerializer.Deserialize<List<PowerUpInstance>>(serialized) ?? new List<PowerUpInstance>();
            return powerUps.Where(p => p.IsActive).ToList();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取地图道具时发生异常 - 游戏ID: {GameId}", gameId);
            return new List<PowerUpInstance>();
        }
    }

    /// <summary>
    /// 更新道具效果状态
    /// </summary>
    public async Task<PowerUpUpdateResult> UpdatePowerUpEffectsAsync(Guid gameId, long deltaTime)
    {
        try
        {
            var result = new PowerUpUpdateResult();
            var gameState = await _gameStateService.GetGameStateAsync(gameId);
            
            // 由于GameStateInfo没有PlayerIds，我们使用一个简化的方法
            // 实际实现中应该从游戏状态或其他地方获取玩家列表
            if (gameState == null) return result;

            var expiredEffectIds = new List<Guid>();
            var currentTime = DateTime.UtcNow;

            // 暂时简化处理，只更新当前有效果的玩家
            // 实际实现中需要从游戏状态获取所有玩家ID
            _logger.LogInformation("更新道具效果 - 游戏ID: {GameId}", gameId);

            result.ExpiredEffectIds = expiredEffectIds;
            
            if (result.ExpiredEffectsCount > 0)
            {
                _logger.LogInformation("道具效果更新完成 - 游戏ID: {GameId}, 活跃: {Active}, 过期: {Expired}", 
                    gameId, result.ActiveEffectsCount, result.ExpiredEffectsCount);
            }

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新道具效果时发生异常 - 游戏ID: {GameId}", gameId);
            throw;
        }
    }

    /// <summary>
    /// 检查护盾是否能阻挡攻击
    /// </summary>
    public async Task<ShieldBlockResult> CheckShieldBlockAsync(Guid gameId, Guid playerId)
    {
        try
        {
            var result = new ShieldBlockResult();

            var activeEffects = await GetActiveEffectsAsync(gameId, playerId);
            var shieldEffect = activeEffects.FirstOrDefault(e => e.Type == TerritoryGamePowerUpType.Shield && e.IsActive);

            if (shieldEffect == null)
            {
                result.HasShield = false;
                return result;
            }

            result.HasShield = true;

            // 检查护盾是否还有阻挡次数
            var blocksRemaining = (int)(shieldEffect.Effects?.GetValueOrDefault("BlocksRemaining", 0) ?? 0);
            
            if (blocksRemaining > 0)
            {
                // 护盾成功阻挡攻击
                result.BlockedAttack = true;
                result.RemainingBlocks = blocksRemaining - 1;

                // 更新剩余阻挡次数
                if (shieldEffect.Effects != null)
                {
                    shieldEffect.Effects["BlocksRemaining"] = result.RemainingBlocks;
                }

                // 如果阻挡次数用完，护盾失效
                if (result.RemainingBlocks <= 0)
                {
                    shieldEffect.IsActive = false;
                    shieldEffect.EndTime = DateTime.UtcNow;
                    result.ShieldExpired = true;
                }

                // 更新效果到Redis
                var allEffects = await GetActiveEffectsAsync(gameId, playerId);
                var effectIndex = allEffects.FindIndex(e => e.EffectId == shieldEffect.EffectId);
                if (effectIndex >= 0)
                {
                    allEffects[effectIndex] = shieldEffect;
                    var serializedEffects = JsonSerializer.Serialize(allEffects);
                    await _redisService.StringSetAsync(
                        $"{string.Format(ACTIVE_EFFECTS_KEY, gameId)}:{playerId}",
                        serializedEffects,
                        TimeSpan.FromHours(1));
                }

                _logger.LogInformation("护盾成功阻挡攻击 - 玩家ID: {PlayerId}, 剩余次数: {Remaining}", 
                    playerId, result.RemainingBlocks);
            }
            else
            {
                result.BlockedAttack = false;
                result.RemainingBlocks = 0;
            }

            result.ShieldEndTime = shieldEffect.EndTime;
            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "检查护盾阻挡时发生异常 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", gameId, playerId);
            throw;
        }
    }

    /// <summary>
    /// 检查幽灵状态
    /// </summary>
    public async Task<bool> IsPlayerInGhostModeAsync(Guid gameId, Guid playerId)
    {
        try
        {
            var activeEffects = await GetActiveEffectsAsync(gameId, playerId);
            var ghostEffect = activeEffects.FirstOrDefault(e => 
                e.Type == TerritoryGamePowerUpType.Ghost && 
                e.IsActive && 
                e.EndTime > DateTime.UtcNow);

            return ghostEffect != null;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "检查幽灵状态时发生异常 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", gameId, playerId);
            return false;
        }
    }

    /// <summary>
    /// 获取玩家当前移动速度
    /// </summary>
    public async Task<float> GetPlayerSpeedMultiplierAsync(Guid gameId, Guid playerId)
    {
        try
        {
            float speedMultiplier = 1.0f;

            var activeEffects = await GetActiveEffectsAsync(gameId, playerId);
            
            foreach (var effect in activeEffects)
            {
                if (effect.Effects?.ContainsKey("SpeedMultiplier") == true)
                {
                    var effectMultiplier = effect.Effects["SpeedMultiplier"];
                    
                    // 根据道具类型处理速度影响
                    switch (effect.Type)
                    {
                        case TerritoryGamePowerUpType.Lightning:
                            // 闪电道具提升速度（乘法）
                            speedMultiplier = Math.Max(speedMultiplier, effectMultiplier);
                            break;
                        case TerritoryGamePowerUpType.Shield:
                            // 护盾道具降低速度（乘法）
                            speedMultiplier *= effectMultiplier;
                            break;
                    }
                }
            }

            return speedMultiplier;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取玩家速度倍率时发生异常 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", gameId, playerId);
            return 1.0f;
        }
    }

    /// <summary>
    /// 清理过期道具
    /// </summary>
    public async Task<int> CleanupExpiredPowerUpsAsync(Guid gameId)
    {
        try
        {
            var serialized = await _redisService.StringGetAsync(string.Format(POWERUPS_KEY, gameId));
            if (string.IsNullOrEmpty(serialized)) return 0;
            
            var allPowerUps = JsonSerializer.Deserialize<List<PowerUpInstance>>(serialized) ?? new List<PowerUpInstance>();
            if (!allPowerUps.Any()) return 0;

            var cutoffTime = DateTime.UtcNow.AddMinutes(-5); // 5分钟前生成的道具视为过期
            var expiredCount = 0;

            var activePowerUps = allPowerUps.Where(p => 
                p.IsActive && p.SpawnTime > cutoffTime).ToList();

            expiredCount = allPowerUps.Count - activePowerUps.Count;

            if (expiredCount > 0)
            {
                var serializedActive = JsonSerializer.Serialize(activePowerUps);
                await _redisService.StringSetAsync(string.Format(POWERUPS_KEY, gameId), serializedActive, TimeSpan.FromHours(1));
                _logger.LogInformation("清理过期道具 - 游戏ID: {GameId}, 清理数量: {Count}", gameId, expiredCount);
            }

            return expiredCount;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "清理过期道具时发生异常 - 游戏ID: {GameId}", gameId);
            return 0;
        }
    }

    /// <summary>
    /// 获取道具刷新配置
    /// </summary>
    public PowerUpSpawnConfig GetPowerUpConfig(string gameMode)
    {
        // 可以从配置文件或数据库获取，这里返回默认配置
        var config = new PowerUpSpawnConfig();

        switch (gameMode?.ToLower())
        {
            case "competitive":
                config.MaxConcurrentPowerUps = 2;
                config.SpawnIntervalSeconds = 30;
                config.SpawnWeights = new Dictionary<TerritoryGamePowerUpType, float>
                {
                    { TerritoryGamePowerUpType.Lightning, 0.35f },
                    { TerritoryGamePowerUpType.Shield, 0.35f },
                    { TerritoryGamePowerUpType.Bomb, 0.15f },
                    { TerritoryGamePowerUpType.Ghost, 0.15f }
                };
                break;
            case "casual":
                config.MaxConcurrentPowerUps = 4;
                config.SpawnIntervalSeconds = 20;
                config.SpawnWeights = new Dictionary<TerritoryGamePowerUpType, float>
                {
                    { TerritoryGamePowerUpType.Lightning, 0.25f },
                    { TerritoryGamePowerUpType.Shield, 0.25f },
                    { TerritoryGamePowerUpType.Bomb, 0.25f },
                    { TerritoryGamePowerUpType.Ghost, 0.25f }
                };
                break;
            default: // standard
                config.MaxConcurrentPowerUps = 3;
                config.SpawnIntervalSeconds = 25;
                break;
        }

        return config;
    }

    /// <summary>
    /// 获取游戏中活跃的道具
    /// 返回地图上可拾取的道具和正在生效的玩家道具效果
    /// </summary>
    public async Task<ActivePowerUpsResult> GetActivePowerUpsAsync(Guid gameId)
    {
        try
        {
            _logger.LogDebug("获取游戏活跃道具 - GameId: {GameId}", gameId);

            var result = new ActivePowerUpsResult { Success = true };

            // 获取地图上的道具
            result.MapPowerUps = await GetMapPowerUpsAsync(gameId);

            // 获取所有玩家的道具和活跃效果
            var gameState = await _gameStateService.GetGameStateAsync(gameId);
            if (gameState != null)
            {
                // 简化处理：由于无法从GameState获取玩家列表，我们尝试从Redis获取游戏玩家
                var playersKey = $"game_players:{gameId}";
                var playerIds = await _redisService.GetSetMembersAsync(playersKey);

                foreach (var playerIdStr in playerIds)
                {
                    if (Guid.TryParse(playerIdStr, out var playerId))
                    {
                        var playerPowerUp = await GetPlayerPowerUpAsync(gameId, playerId);
                        var activeEffects = await GetActiveEffectsAsync(gameId, playerId);
                        
                        // 获取玩家名称（简化处理）
                        var playerName = await GetPlayerNameAsync(gameId, playerId);

                        var playerPowerUpInfo = new PlayerPowerUpInfo
                        {
                            PlayerId = playerId,
                            PlayerName = playerName,
                            HeldPowerUp = playerPowerUp,
                            ActiveEffects = activeEffects
                        };

                        result.PlayerPowerUps.Add(playerPowerUpInfo);
                        result.ActiveEffects.AddRange(activeEffects);
                    }
                }
            }

            _logger.LogDebug("获取活跃道具成功 - GameId: {GameId}, MapPowerUps: {MapCount}, PlayerPowerUps: {PlayerCount}, ActiveEffects: {EffectCount}", 
                gameId, result.MapPowerUps.Count, result.PlayerPowerUps.Count, result.ActiveEffects.Count);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取游戏活跃道具失败 - GameId: {GameId}", gameId);
            return new ActivePowerUpsResult
            {
                Success = false,
                Errors = { "获取活跃道具时发生内部错误" }
            };
        }
    }

    /// <summary>
    /// 获取玩家名称的辅助方法
    /// </summary>
    private async Task<string> GetPlayerNameAsync(Guid gameId, Guid playerId)
    {
        try
        {
            var stateKey = $"player_state:{gameId}:{playerId}";
            var playerName = await _redisService.HashGetAsync(stateKey, "player_name");
            return !string.IsNullOrEmpty(playerName) ? playerName : "Unknown Player";
        }
        catch
        {
            return "Unknown Player";
        }
    }

    #region 私有辅助方法

    /// <summary>
    /// 选择随机道具类型
    /// </summary>
    private TerritoryGamePowerUpType SelectRandomPowerUpType(Dictionary<TerritoryGamePowerUpType, float> weights)
    {
        var random = _random.NextDouble();
        var cumulative = 0f;

        foreach (var kvp in weights)
        {
            cumulative += kvp.Value;
            if (random <= cumulative)
            {
                return kvp.Key;
            }
        }

        return TerritoryGamePowerUpType.Lightning; // 默认返回闪电
    }

    /// <summary>
    /// 寻找最佳生成位置
    /// </summary>
    private async Task<Position?> FindOptimalSpawnPosition(Guid gameId, bool excludeOccupiedAreas)
    {
        try
        {
            // 这里应该根据实际地图大小和玩家分布来计算最佳位置
            // 目前使用简化的随机生成逻辑
            const int mapWidth = 800;
            const int mapHeight = 600;
            const int margin = 50;

            for (int attempts = 0; attempts < 20; attempts++)
            {
                var position = new Position
                {
                    X = _random.Next(margin, mapWidth - margin),
                    Y = _random.Next(margin, mapHeight - margin)
                };

                // 检查位置是否合适（不在玩家密集区域）
                if (excludeOccupiedAreas)
                {
                    var ownership = await _territoryService.CheckTerritoryOwnershipAsync(gameId, position);
                    if (ownership.IsOwned) continue; // 跳过已占领区域
                }

                // 检查与现有道具的距离（至少间隔100像素）
                var existingPowerUps = await GetMapPowerUpsAsync(gameId);
                bool tooClose = existingPowerUps.Any(p => 
                    CalculateDistance(position, p.Position) < 100);

                if (!tooClose)
                {
                    return position;
                }
            }

            // 如果找不到合适位置，返回一个随机位置
            return new Position
            {
                X = _random.Next(margin, mapWidth - margin),
                Y = _random.Next(margin, mapHeight - margin)
            };
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 计算两点间距离
    /// </summary>
    private float CalculateDistance(Position pos1, Position pos2)
    {
        var dx = pos1.X - pos2.X;
        var dy = pos1.Y - pos2.Y;
        return (float)Math.Sqrt(dx * dx + dy * dy);
    }

    /// <summary>
    /// 生成圆形区域的点
    /// </summary>
    private List<Position> GenerateCirclePoints(Position center, float radius)
    {
        var points = new List<Position>();
        var radiusSquared = radius * radius;

        for (int x = (int)(center.X - radius); x <= center.X + radius; x++)
        {
            for (int y = (int)(center.Y - radius); y <= center.Y + radius; y++)
            {
                var distanceSquared = Math.Pow(x - center.X, 2) + Math.Pow(y - center.Y, 2);
                if (distanceSquared <= radiusSquared)
                {
                    points.Add(new Position { X = x, Y = y });
                }
            }
        }

        return points;
    }

    /// <summary>
    /// 获取道具颜色
    /// </summary>
    private string GetPowerUpColor(TerritoryGamePowerUpType type)
    {
        return type switch
        {
            TerritoryGamePowerUpType.Lightning => "#00BFFF", // 蓝色
            TerritoryGamePowerUpType.Shield => "#FFD700",    // 金色
            TerritoryGamePowerUpType.Bomb => "#FF4500",      // 红色
            TerritoryGamePowerUpType.Ghost => "#9370DB",     // 紫色
            _ => "#FFFFFF"
        };
    }

    /// <summary>
    /// 获取道具图标
    /// </summary>
    private string GetPowerUpIcon(TerritoryGamePowerUpType type)
    {
        return type switch
        {
            TerritoryGamePowerUpType.Lightning => "⚡",
            TerritoryGamePowerUpType.Shield => "🛡️",
            TerritoryGamePowerUpType.Bomb => "💣",
            TerritoryGamePowerUpType.Ghost => "👻",
            _ => "❓"
        };
    }

    /// <summary>
    /// 获取道具名称
    /// </summary>
    private string GetPowerUpName(TerritoryGamePowerUpType type)
    {
        return type switch
        {
            TerritoryGamePowerUpType.Lightning => "闪电",
            TerritoryGamePowerUpType.Shield => "护盾",
            TerritoryGamePowerUpType.Bomb => "炸弹",
            TerritoryGamePowerUpType.Ghost => "幽灵",
            _ => "未知道具"
        };
    }

    /// <summary>
    /// 获取道具属性
    /// </summary>
    private Dictionary<string, object> GetPowerUpProperties(TerritoryGamePowerUpType type)
    {
        return type switch
        {
            TerritoryGamePowerUpType.Lightning => new Dictionary<string, object>
            {
                { "SpeedBoost", 0.6f },
                { "Duration", 8 },
                { "TrailThickness", 3f }
            },
            TerritoryGamePowerUpType.Shield => new Dictionary<string, object>
            {
                { "Blocks", 1 },
                { "Duration", 12 },
                { "SpeedPenalty", 0.1f }
            },
            TerritoryGamePowerUpType.Bomb => new Dictionary<string, object>
            {
                { "Radius", 30f },
                { "InstantUse", true }
            },
            TerritoryGamePowerUpType.Ghost => new Dictionary<string, object>
            {
                { "Duration", 10 },
                { "CanPassTrails", true },
                { "CanDraw", false }
            },
            _ => new Dictionary<string, object>()
        };
    }

    /// <summary>
    /// 消耗玩家道具
    /// </summary>
    private async Task ConsumePowerUpAsync(Guid gameId, Guid playerId)
    {
        var key = $"{string.Format(PLAYER_POWERUPS_KEY, gameId)}:{playerId}";
        await _redisService.KeyDeleteAsync(key);
    }

    #endregion
}